package com.ledim.ledimview;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ledim.bean.LedimVedioTagBean;
import com.ledim.bean.base.BaseResultDataInfo;
import com.ledim.itf.LedimAlbusFragmentInterface;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.LedimFunctionUtils;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.LoadingBar;
import com.letv.android.young.client.R;
import java.util.ArrayList;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class VideoTagsView extends LinearLayout implements View.OnClickListener {

    private View mAddTags;
    private View mTagsEmpty;
    private TextView mTagTitle;
    private TagsFlowView mTagsView;
    private Context mContext;
    private AnimationDrawable mAnimationDrawable;
    private ArrayList<LedimVedioTagBean> mTagsList = new ArrayList<LedimVedioTagBean>(); // 标签数组
    private LedimAlbusFragmentInterface mAlbusInterface;
    private LoadingBar mLoading;

    public VideoTagsView(Context context) {
        super(context);
        mContext = context;
    }

    public VideoTagsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public VideoTagsView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        //        init();
    }

    //绑定数据
    public void bindData(ArrayList<LedimVedioTagBean> mTagsList,
                         LedimAlbusFragmentInterface albusInterface) {
        this.mTagsList = mTagsList;
        mAlbusInterface = albusInterface;
        init();
    }

    /**
     * 初始化界面
     */
    private void init() {
        mAddTags = findViewById(R.id.video_add_tags);
        mTagsEmpty = findViewById(R.id.tags_emptyLayout);
        mTagTitle = (TextView) findViewById(R.id.video_add_episode);
        mTagsView = (TagsFlowView) findViewById(R.id.tags_flowlayout);
        mAddTags.setOnClickListener(this);
        mTagTitle.setOnClickListener(this);
        if (mTagsList.size() != 0) {
            showTagsView(mTagsList);
            mTagsEmpty.setVisibility(View.GONE);
            mTagsView.setVisibility(View.VISIBLE);
        } else {
            mTagsEmpty.setVisibility(View.VISIBLE);
            mTagsView.setVisibility(View.GONE);
        }

    }

    //显示标签
    private void showTagsView(final ArrayList<LedimVedioTagBean> mTagsList) {
        mTagsView.removeAllViews();
        //标签边距参数
        MarginLayoutParams lp =
                new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 0;
        lp.rightMargin = 0;
        lp.topMargin = 0;
        lp.bottomMargin = 0;
        for (int i = 0; i < mTagsList.size(); i++) {
            final View view = View.inflate(mContext, R.layout.item_tags, null);
            view.setTag(i);
            LedimVedioTagBean ledimVedioTagBean = mTagsList.get(i);
            final View mBg = view.findViewById(R.id.tags_layout);
            final TextView mNameView = (TextView) view.findViewById(R.id.tags_name);
            final TextView mNumView = (TextView) view.findViewById(R.id.tags_num);
            final ImageView mImage = (ImageView) view.findViewById(R.id.tags_like);
            mNameView.setText(ledimVedioTagBean.title);
            LogUtil.e("ccx ledimVedioTagBean:tagname=" + ledimVedioTagBean.title +
                    ",ledimVedioTagBean liked==" + ledimVedioTagBean.is_liked);
            if (ledimVedioTagBean.is_liked) {
                setTagsBg(mBg, mNameView, mNumView, mImage, false);
            }
            double likes_count = mTagsList.get(i).likes_count;
            if (likes_count == 0) {
                mNumView.setVisibility(View.GONE);
            } else {
                mNumView.setVisibility(View.VISIBLE);
                if (likes_count < 10000) {
                    mNumView.setText((int) likes_count + "");
                } else {
                    mNumView.setText(((int) (likes_count / 1000)) / 10.0 + "万");
                }
            }
            mTagsView.addView(view, lp);

            //给每个标签设置监听
            view.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    if (!LedimSpUtils.isLogin()) {
                        LedimFunctionUtils.showLoginDialog((FragmentActivity) mContext);
                    } else {
                        int index = (Integer) (view.getTag());
                        if (!mTagsList.get(index).is_liked) {
                            mNumView.setVisibility(View.VISIBLE);
                            if (mTagsList.get(index).likes_count + 1 < 10000) {
                                mNumView.setText(
                                        (mTagsList.get(index).likes_count + 1) + "");//人为显示+1
                            } else if (mTagsList.get(index).likes_count + 1 == 10000) {
                                mNumView.setText("1.0万");
                            } else {
                                mNumView.setText(
                                        (mTagsList.get(index).likes_count + 1) / 1000 / 10.0 + "万");
                            }
                            setTagsBg(mBg, mNameView, mNumView, mImage, true);
                            likeTag(mTagsList.get(index).id);
                        } else {
                            ToastUtil.toast("这个标签已被您占有过了~");
                        }
                    }

                }
            });
        }

    }

    public void createTags(String mTagKey, String aid, String vid) {
        if (aid.equals("0")) {
            createTag(vid, mTagKey, 1 + "");
        } else {
            createTag(aid, mTagKey, 2 + "");
        }

    }

    /**
     * 赞标签
     *
     * @param id
     */
    private void likeTag(String id) {
        LedimApiServiceFactory.createService(ApiService.class)
                              .likeTag(id)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<LedimVedioTagBean>>() {
                                 @Override
                                 public void onCompleted() {
                                     super.onCompleted();
                                 }

                                 @Override
                                 public void onError(Throwable e) {
                                     super.onError(e);
                                     LogUtil.e(e.getMessage());
                                 }

                                 @Override
                                 public void onNext(
                                         final BaseResultDataInfo<LedimVedioTagBean> data) {
                                     super.onNext(data);
                                     if (data != null) {
                                         if (data.success) {
                                             //按照之前的逻辑，不进行处理

                                         } else {
                                             ToastUtil.toast(data.message);
                                         }
                                     }
                                 }
                             });

    }

    /**
     * 创建标签
     */
    private void createTag(String id, String title, String type) {
        if (mLoading == null) {
            mLoading = new LoadingBar((Activity) mContext);
        }
        mLoading.show();
        LedimApiServiceFactory.createService(ApiService.class)
                              .createTag(id, title, type)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<LedimVedioTagBean>>() {
                                 @Override
                                 public void onCompleted() {
                                     super.onCompleted();
                                 }

                                 @Override
                                 public void onError(Throwable e) {
                                     super.onError(e);
                                     mLoading.dismiss();
                                     LogUtil.e(e.getMessage());
                                 }

                                 @Override
                                 public void onNext(
                                         final BaseResultDataInfo<LedimVedioTagBean> data) {
                                     super.onNext(data);
                                     mLoading.dismiss();
                                     if (data != null) {
                                         if (data.success) {
                                             //成功
                                             mTagsEmpty.setVisibility(View.GONE);
                                             mTagsView.setVisibility(View.VISIBLE);
                                             //创建标签
                                             ToastUtil.toast("好了，大王！");
                                             MarginLayoutParams lp =
                                                     new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                                             lp.leftMargin = 0;
                                             lp.rightMargin = 0;
                                             lp.topMargin = 0;
                                             lp.bottomMargin = 0;

                                             final View view =
                                                     View.inflate(mContext, R.layout.item_tags, null);
                                             final View mBg = view.findViewById(R.id.tags_layout);
                                             final TextView mNameView =
                                                     (TextView) view.findViewById(R.id.tags_name);
                                             final TextView mNumView =
                                                     (TextView) view.findViewById(R.id.tags_num);
                                             final ImageView mImage =
                                                     (ImageView) view.findViewById(R.id.tags_like);

                                             setTagsBg(mBg, mNameView, mNumView, mImage, false);

                                             mNameView.setText(data.data.title);
                                             if (data.data.likes_count == 0) {
                                                 mNumView.setVisibility(View.GONE);
                                             } else {
                                                 mNumView.setVisibility(View.VISIBLE);
                                                 mNumView.setText(data.data.likes_count + "");
                                             }
                                             mTagsView.addView(view, lp);
                                             view.setOnClickListener(new OnClickListener() {

                                                 public void onClick(View v) {
                                                     if (!data.data.is_liked) {
                                                         mNumView.setVisibility(View.VISIBLE);
                                                         mNumView.setText(
                                                                 (data.data.likes_count + 1) +
                                                                         "");//人为显示+1

                                                         setTagsBg(mBg, mNameView, mNumView, mImage, true);
                                                         likeTag(data.data.id);
                                                     }
                                                 }
                                             });
                                         } else {
                                             ToastUtil.toast(data.message);
                                         }
                                         mAlbusInterface.closeAddTagsView();
                                     } 
                                 }
                             });

    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_add_episode:
            case R.id.video_add_tags:
                if (!LedimSpUtils.isLogin()) {
                    LedimFunctionUtils.showLoginDialog((FragmentActivity) mContext);
                } else {
                    mAlbusInterface.onAddTagsClick();
                }
                break;
        }
    }

    //设置标签背景
    private void setTagsBg(View mBg, TextView mNameView, TextView mNumView, ImageView mImage,
                           boolean flag) {
        if (flag) {
            mImage.setBackgroundResource(R.anim.frame_heart);
            mAnimationDrawable = (AnimationDrawable) mImage.getBackground();
            mAnimationDrawable.start();
        } else {
            mImage.setImageResource(R.drawable.heart_4);
        }
        mBg.setBackgroundResource(R.drawable.rect_round_tag_bg1);
        mNameView.setTextColor(Color.parseColor("#333333"));
        mNumView.setTextColor(Color.parseColor("#FA5F5F"));
    }

}
